#!/bin/bash

# 版本一致性检查脚本
# 🎯 重构说明: 确保所有文件中的版本号都是v0.7.0
# 🔧 兼容性保证: 验证版本号的一致性，避免版本混乱

set -e

EXPECTED_VERSION="0.7.0"
ERRORS=0

echo "🔍 版本一致性检查"
echo "期望版本: v${EXPECTED_VERSION}"
echo "================================"

# 检查 cjpm.toml
echo "📋 1. 检查 cjpm.toml..."
CJPM_VERSION=$(grep "^version = " cjpm.toml | sed 's/version = "\(.*\)"/\1/')
if [ "$CJPM_VERSION" = "$EXPECTED_VERSION" ]; then
    echo "✅ cjpm.toml: v${CJPM_VERSION}"
else
    echo "❌ cjpm.toml: v${CJPM_VERSION} (期望: v${EXPECTED_VERSION})"
    ERRORS=$((ERRORS + 1))
fi

# 检查 README.md
echo "📋 2. 检查 README.md..."
README_VERSION=$(grep "version-" README.md | sed 's/.*version-\([0-9.]*\).*/\1/')
if [ "$README_VERSION" = "$EXPECTED_VERSION" ]; then
    echo "✅ README.md: v${README_VERSION}"
else
    echo "❌ README.md: v${README_VERSION} (期望: v${EXPECTED_VERSION})"
    ERRORS=$((ERRORS + 1))
fi

# 检查 CHANGELOG.md
echo "📋 3. 检查 CHANGELOG.md..."
CHANGELOG_VERSION=$(grep "^## \[" CHANGELOG.md | head -1 | sed 's/## \[\([0-9.]*\)\].*/\1/')
if [ "$CHANGELOG_VERSION" = "$EXPECTED_VERSION" ]; then
    echo "✅ CHANGELOG.md: v${CHANGELOG_VERSION}"
else
    echo "❌ CHANGELOG.md: v${CHANGELOG_VERSION} (期望: v${EXPECTED_VERSION})"
    ERRORS=$((ERRORS + 1))
fi

# 检查源代码中的版本标记
echo "📋 4. 检查源代码版本标记..."
SOURCE_VERSIONS=$(grep -r "v0\.[0-9]\+\.[0-9]\+" src/ --include="*.cj" | grep -o "v[0-9]\+\.[0-9]\+\.[0-9]\+" | sort | uniq)
INCONSISTENT_VERSIONS=""

for version in $SOURCE_VERSIONS; do
    if [ "$version" != "v${EXPECTED_VERSION}" ]; then
        INCONSISTENT_VERSIONS="$INCONSISTENT_VERSIONS $version"
    fi
done

if [ -z "$INCONSISTENT_VERSIONS" ]; then
    echo "✅ 源代码版本标记: 全部为 v${EXPECTED_VERSION}"
else
    echo "❌ 源代码版本标记: 发现不一致的版本: $INCONSISTENT_VERSIONS"
    echo "   详细信息:"
    grep -r "v0\.[0-9]\+\.[0-9]\+" src/ --include="*.cj" | grep -v "v${EXPECTED_VERSION}" | head -5
    ERRORS=$((ERRORS + 1))
fi

# 检查文档中的版本号
echo "📋 5. 检查文档版本号..."
DOC_VERSIONS=$(grep -r "v0\.[0-9]\+\.[0-9]\+" docs/ --include="*.md" 2>/dev/null | grep -o "v[0-9]\+\.[0-9]\+\.[0-9]\+" | sort | uniq || true)
DOC_INCONSISTENT=""

for version in $DOC_VERSIONS; do
    if [ "$version" != "v${EXPECTED_VERSION}" ]; then
        DOC_INCONSISTENT="$DOC_INCONSISTENT $version"
    fi
done

if [ -z "$DOC_INCONSISTENT" ]; then
    echo "✅ 文档版本号: 全部为 v${EXPECTED_VERSION} 或无版本号"
else
    echo "❌ 文档版本号: 发现不一致的版本: $DOC_INCONSISTENT"
    ERRORS=$((ERRORS + 1))
fi

# 总结
echo "================================"
if [ $ERRORS -eq 0 ]; then
    echo "🎉 版本一致性检查通过！"
    echo "所有文件的版本号都是 v${EXPECTED_VERSION}"
    exit 0
else
    echo "❌ 版本一致性检查失败！"
    echo "发现 ${ERRORS} 个版本不一致的问题"
    echo ""
    echo "🔧 修复建议:"
    echo "1. 更新所有不一致的版本号为 v${EXPECTED_VERSION}"
    echo "2. 重新运行此脚本验证"
    exit 1
fi
